<?php

/*
=====================================================
 FluxBB - Delux Board Converstations (DBC)
-----------------------------------------------------
 http://dbc-forum.com/
 http://fluxbb.org/
-----------------------------------------------------
 Copyright (c) 2010,2011 FluxBB - Delux Board Conversations (DBC)
-----------------------------------------------------
 Предсловие: Данный скрипт (DBC) не является работой с нуля, то 
 есть ядром скрипта всё также остаётся FuxBB,но теперь в оболочке
 DBC.
=====================================================
*/

define('DBC_ROOT', './');
require DBC_ROOT.'engine/common.php';

if ($DBC_user['g_read_board'] == '0')
	message($lang_common['No view']);

if ($DBC_user['is_guest'] && $DBC_config['o_blocking_time'] != '0')
{
	$block_time_term = time() - 60 * $DBC_config['o_blocking_time'];
	$db->query('DELETE FROM '.$db->prefix.'blocking WHERE block_log < '.$block_time_term) or error('Unable to delete from blocking list', __FILE__, __LINE__, $db->error());
	$block_q = ($DBC_config['o_blocking_guest'] == '1') ? '' : ' AND block_type=3';
	$result = $db->query('SELECT block_ip FROM '.$db->prefix.'blocking WHERE block_ip=\''.$db->escape(get_remote_address()).'\''.$block_q) or error('Unable to fetch blocking info', __FILE__, __LINE__, $db->error());
	$block_kolvo = $db->num_rows($result);
	if ($block_kolvo > $DBC_config['o_blocking_kolvo'])
		message($lang_common['Limit of errors']);
}

$tid = isset($_GET['tid']) ? intval($_GET['tid']) : 0;
$fid = isset($_GET['fid']) ? intval($_GET['fid']) : 0;
if ($tid < 1 && $fid < 1 || $tid > 0 && $fid > 0)
	message($lang_common['Bad request']);

// Fetch some info about the topic and/or the forum
//	$result = $db->query('SELECT f.id, f.forum_name, f.moderators, f.redirect_url, fp.post_replies, fp.post_topics, t.subject, t.topic_desc, t.closed, s.user_id AS is_subscribed FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$DBC_user['g_id'].') LEFT JOIN '.$db->prefix.'subscriptions AS s ON (t.id=s.topic_id AND s.user_id='.$DBC_user['id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.id='.$tid) or error('Unable to fetch forum info', __FILE__, __LINE__, $db->error());
// f.no_sum_mess,
if ($tid)
	$result = $db->query('SELECT f.id, f.forum_name, f.moderators, f.redirect_url, f.no_sum_mess, fp.post_replies, fp.post_topics, t.subject, t.topic_desc, t.closed, p.id AS post_id, p.poster_id, p.message, p.posted, s.user_id AS is_subscribed FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'posts AS p ON (t.last_post_id=p.id AND p.poster_id='.$DBC_user['id'].') LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$DBC_user['g_id'].') LEFT JOIN '.$db->prefix.'subscriptions AS s ON (t.id=s.topic_id AND s.user_id='.$DBC_user['id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.id='.$tid) or error('Unable to fetch forum info', __FILE__, __LINE__, $db->error());
else
	$result = $db->query('SELECT f.id, f.forum_name, f.moderators, f.redirect_url, f.no_sum_mess, fp.post_replies, fp.post_topics FROM '.$db->prefix.'forums AS f LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$DBC_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND f.id='.$fid) or error('Unable to fetch forum info', __FILE__, __LINE__, $db->error());

if (!$db->num_rows($result))
	message($lang_common['Bad request']);

$cur_posting = $db->fetch_assoc($result);
$is_subscribed = $tid && $cur_posting['is_subscribed'];

// Is someone trying to post into a redirect forum?
if ($cur_posting['redirect_url'] != '')
	message($lang_common['Bad request']);

// Sort out who the moderators are and if we are currently a moderator (or an admin)
$mods_array = ($cur_posting['moderators'] != '') ? unserialize($cur_posting['moderators']) : array();
$is_admmod = ($DBC_user['g_id'] == DBC_ADMIN || ($DBC_user['g_moderator'] == '1' && array_key_exists($DBC_user['username'], $mods_array))) ? true : false;

if ($tid && $DBC_config['o_censoring'] == '1')
	$cur_posting['subject'] = censor_words($cur_posting['subject']);
	$cur_posting['topic_desc'] = censor_words($cur_posting['topic_desc']);

// Do we have permission to post?
if ((($tid && (($cur_posting['post_replies'] == '' && $DBC_user['g_post_replies'] == '0') || $cur_posting['post_replies'] == '0')) ||
	($fid && (($cur_posting['post_topics'] == '' && $DBC_user['g_post_topics'] == '0') || $cur_posting['post_topics'] == '0')) ||
	(isset($cur_posting['closed']) && $cur_posting['closed'] == '1')) &&
	!$is_admmod)
	message($lang_common['No permission']);

// Load the post.php language file
require DBC_ROOT.'language/'.$DBC_user['language'].'/post.php';

// Start with a clean slate
$errors = array();

// Did someone just hit "Submit" or "Preview"?

if (isset($_POST['form_sent']))
{
	// Make sure form_user is correct
	if (($DBC_user['is_guest'] && $_POST['form_user'] != 'Guest') || (!$DBC_user['is_guest'] && $_POST['form_user'] != $DBC_user['username']))
		message($lang_common['Bad request']);

	// Flood protection
	if (!isset($_POST['preview']) && $DBC_user['last_post'] != '' && (time() - $DBC_user['last_post']) < $DBC_user['g_post_flood'])
		$errors[] = $lang_post['Flood start'].' '.$DBC_user['g_post_flood'].' '.$lang_post['flood end'];

	// If it's a new topic
	if ($fid)
	{
		$subject = DBC_trim($_POST['req_subject']);
		$topic_desc = DBC_trim($_POST['topic_desc']);

		if ($subject == '')
			$errors[] = $lang_post['No subject'];
		else if (DBC_strlen($subject) > 70)
			$errors[] = $lang_post['Too long subject'];
		else if ($DBC_config['p_subject_all_caps'] == '0' && is_all_uppercase($subject) && !$DBC_user['is_admmod'])
			$errors[] = $lang_post['All caps subject'];
	}

	// If the user is logged in we get the username and email from $DBC_user
	if (!$DBC_user['is_guest'])
	{
		$username = $DBC_user['username'];
		$email = $DBC_user['email'];
		$id = $DBC_user['id'];
	}
	// Otherwise it should be in $_POST
	else
	{
		$username = DBC_trim($_POST['req_username']);
		$email = strtolower(trim(($DBC_config['p_force_guest_email'] == '1') ? $_POST['req_email'] : $_POST['email']));

		// Load the register.php/profile.php language files
		require DBC_ROOT.'language/'.$DBC_user['language'].'/prof_reg.php';
		require DBC_ROOT.'language/'.$DBC_user['language'].'/register.php';

		confirm_referrer('post.php');

		$vform_sent = intval($_POST['form_sent']);
		if ($vform_sent == 1 || $vform_sent > time() || (time() - $vform_sent > 1800) || (time() - $vform_sent < 6))
			$errors[] = $lang_prof_reg['You are robot'];

		// It's a guest, so we have to validate the username
		check_username($username);

		if ($DBC_config['p_force_guest_email'] == '1' || $email != '')
		{
			require DBC_ROOT.'engine/email.php';
			if (!is_valid_email($email))
				$errors[] = $lang_common['Invalid email'];

			// Check if it's a banned email address
			// we should only check guests because members addresses are already verified
			if ($DBC_user['is_guest'] && is_banned_email($email))
			{
				if ($DBC_config['p_allow_banned_email'] == '0')
					$errors[] = $lang_prof_reg['Banned email'];

				$banned_email = true; // Used later when we send an alert email
			}
			else
				$banned_email = false;
		}
	}

	// Clean up message from POST
	$message = DBC_linebreaks(DBC_trim($_POST['req_message']));

	$merged = false;

	if (DBC_strlen($message) > DBC_MAX_POSTSIZE)
		$errors[] = sprintf($lang_post['Too long message'], forum_number_format(DBC_MAX_POSTSIZE));
	else if ($DBC_config['p_message_all_caps'] == '0' && is_all_uppercase($message) && !$DBC_user['is_admmod'])
		$errors[] = $lang_post['All caps message'];

	// Validate BBCode syntax
	if ($DBC_config['p_message_bbcode'] == '1')
	{
		require DBC_ROOT.'engine/parser.php';
		$message = preparse_bbcode($message, $errors);
	}

	if ($message == '')
		$errors[] = $lang_post['No message'];

	$hide_smilies = isset($_POST['hide_smilies']) ? '1' : '0';
	$subscribe = isset($_POST['subscribe']) ? '1' : '0';

	$now = time();

	// Did everything go according to plan?
	if (empty($errors) && !isset($_POST['preview']))
	{
		require DBC_ROOT.'engine/search_idx.php';

// START Merge Post
		if (isset($DBC_config['o_merge_timeout']) && !$DBC_user['is_guest'] && !$fid && (($is_admmod && isset($_POST['merge']) && intval($_POST['merge'])==1) || !$is_admmod) && $cur_posting['poster_id']!=NULL && $cur_posting['message']!=NULL && ($now - $cur_posting['posted'])<$DBC_config['o_merge_timeout'] && (DBC_strlen($cur_posting['message'].$message) + 100 < DBC_MAX_POSTSIZE))
		{
			$message= '[after='.($now - $cur_posting['posted']).']'."\n".$message;
			$merged = true;
		}
// END Merge Post

		// If it's a reply
		if ($tid)
		{
			if (!$DBC_user['is_guest'])
			{
				$new_tid = $tid;

// START Merge Post
				if (!$merged)
				{
				// Insert the new post
					$db->query('INSERT INTO '.$db->prefix.'posts (poster, poster_id, poster_ip, message, hide_smilies, posted, topic_id, user_agent) VALUES(\''.$db->escape($username).'\', '.$DBC_user['id'].', \''.get_remote_address().'\', \''.$db->escape($message).'\', '.$hide_smilies.', '.$now.', '.$tid.', \''.$db->escape($_SERVER['HTTP_USER_AGENT']).'\')') or error('Unable to create post', __FILE__, __LINE__, $db->error());
					$new_pid = $db->insert_id();
				}
				else
        {
					$message = $cur_posting['message'] . "\n\n" . $message;
					$db->query('UPDATE '.$db->prefix.'posts SET message=\''.$db->escape($message).'\' WHERE  id='.$cur_posting['post_id']) or error('Unable to merge post', __FILE__, __LINE__, $db->error());
					$new_pid = $cur_posting['post_id'];
				}
// END Merge Post

				// To subscribe or not to subscribe, that ...
				if ($DBC_config['o_subscriptions'] == '1')
				{
					if ($subscribe && !$is_subscribed)
						$db->query('INSERT INTO '.$db->prefix.'subscriptions (user_id, topic_id) VALUES('.$DBC_user['id'].' ,'.$tid.')') or error('Unable to add subscription', __FILE__, __LINE__, $db->error());
					else if (!$subscribe && $is_subscribed)
						$db->query('DELETE FROM '.$db->prefix.'subscriptions WHERE user_id='.$DBC_user['id'].' AND topic_id='.$tid) or error('Unable to remove subscription', __FILE__, __LINE__, $db->error());
				}
			}
			else
			{
				// It's a guest. Insert the new post
				$email_sql = ($DBC_config['p_force_guest_email'] == '1' || $email != '') ? '\''.$email.'\'' : 'NULL';
				$db->query('INSERT INTO '.$db->prefix.'posts (poster, poster_ip, poster_email, message, hide_smilies, posted, topic_id, user_agent) VALUES(\''.$db->escape($username).'\', \''.get_remote_address().'\', '.$email_sql.', \''.$db->escape($message).'\', '.$hide_smilies.', '.$now.', '.$tid.', \''.$db->escape($_SERVER['HTTP_USER_AGENT']).'\')') or error('Unable to create post', __FILE__, __LINE__, $db->error());
				$new_pid = $db->insert_id();
			}

			// Count number of replies in the topic
			$result = $db->query('SELECT COUNT(id) FROM '.$db->prefix.'posts WHERE topic_id='.$tid) or error('Unable to fetch post count for topic', __FILE__, __LINE__, $db->error());
			$num_replies = $db->result($result, 0) - 1;

			// Update topic
			$db->query('UPDATE '.$db->prefix.'topics SET num_replies='.$num_replies.', last_post='.$now.', last_post_id='.$new_pid.', last_poster=\''.$db->escape($username).'\' , last_poster_id=\''.$db->escape($id).'\' WHERE id='.$tid) or error('Unable to update topic', __FILE__, __LINE__, $db->error());

			update_search_index('post', $new_pid, $message);

			update_forum($cur_posting['id']);

// START Merge Post
			// Should we send out notifications?
//			if ($DBC_config['o_subscriptions'] == '1')
// END Merge Post
			if ($DBC_config['o_subscriptions'] == '1' && !$merged)
			{
				// Get the post time for the previous post in this topic
				$result = $db->query('SELECT posted FROM '.$db->prefix.'posts WHERE topic_id='.$tid.' ORDER BY id DESC LIMIT 1, 1') or error('Unable to fetch post info', __FILE__, __LINE__, $db->error());
				$previous_post_time = $db->result($result);

				// Get any subscribed users that should be notified (banned users are excluded)
				$result = $db->query('SELECT u.id, u.email, u.notify_with_post, u.language FROM '.$db->prefix.'users AS u INNER JOIN '.$db->prefix.'subscriptions AS s ON u.id=s.user_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id='.$cur_posting['id'].' AND fp.group_id=u.group_id) LEFT JOIN '.$db->prefix.'online AS o ON u.id=o.user_id LEFT JOIN '.$db->prefix.'bans AS b ON u.username=b.username WHERE b.username IS NULL AND COALESCE(o.logged, u.last_visit)>'.$previous_post_time.' AND (fp.read_forum IS NULL OR fp.read_forum=1) AND s.topic_id='.$tid.' AND u.id!='.$DBC_user['id']) or error('Unable to fetch subscription info', __FILE__, __LINE__, $db->error());
				if ($db->num_rows($result))
				{
					require_once DBC_ROOT.'engine/email.php';

					$notification_emails = array();

					// Loop through subscribed users and send emails
					while ($cur_subscriber = $db->fetch_assoc($result))
					{
						// Is the subscription email for $cur_subscriber['language'] cached or not?
						if (!isset($notification_emails[$cur_subscriber['language']]))
						{
							if (file_exists(DBC_ROOT.'lang/'.$cur_subscriber['language'].'/mail_templates/new_reply.tpl'))
							{
								// Load the "new reply" template
								$mail_tpl = trim(file_get_contents(DBC_ROOT.'lang/'.$cur_subscriber['language'].'/mail_templates/new_reply.tpl'));

								// Load the "new reply full" template (with post included)
								$mail_tpl_full = trim(file_get_contents(DBC_ROOT.'lang/'.$cur_subscriber['language'].'/mail_templates/new_reply_full.tpl'));

								// The first row contains the subject (it also starts with "Subject:")
								$first_crlf = strpos($mail_tpl, "\n");
								$mail_subject = trim(substr($mail_tpl, 8, $first_crlf-8));
								$mail_message = trim(substr($mail_tpl, $first_crlf));

								$first_crlf = strpos($mail_tpl_full, "\n");
								$mail_subject_full = trim(substr($mail_tpl_full, 8, $first_crlf-8));
								$mail_message_full = trim(substr($mail_tpl_full, $first_crlf));

								$mail_subject = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_subject);
								$mail_message = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_message);
								$mail_message = str_replace('<replier>', $username, $mail_message);
								$mail_message = str_replace('<post_url>', $DBC_config['o_base_url'].'/topics_'.$new_pid.'#p'.$new_pid, $mail_message);
								$mail_message = str_replace('<unsubscribe_url>', $DBC_config['o_base_url'].'/misc.php?unsubscribe='.$tid, $mail_message);
								$mail_message = str_replace('<board_mailer>', $DBC_config['o_board_title'].' '.$lang_common['Mailer'], $mail_message);

								$mail_subject_full = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_subject_full);
								$mail_message_full = str_replace('<topic_subject>', '\''.$cur_posting['subject'].'\'', $mail_message_full);
								$mail_message_full = str_replace('<replier>', $username, $mail_message_full);
								$mail_message_full = str_replace('<message>', $message, $mail_message_full);
								$mail_message_full = str_replace('<post_url>', $DBC_config['o_base_url'].'/topics_'.$new_pid.'#p'.$new_pid, $mail_message_full);
								$mail_message_full = str_replace('<unsubscribe_url>', $DBC_config['o_base_url'].'/misc.php?unsubscribe='.$tid, $mail_message_full);
								$mail_message_full = str_replace('<board_mailer>', $DBC_config['o_board_title'].' '.$lang_common['Mailer'], $mail_message_full);

								$notification_emails[$cur_subscriber['language']][0] = $mail_subject;
								$notification_emails[$cur_subscriber['language']][1] = $mail_message;
								$notification_emails[$cur_subscriber['language']][2] = $mail_subject_full;
								$notification_emails[$cur_subscriber['language']][3] = $mail_message_full;

								$mail_subject = $mail_message = $mail_subject_full = $mail_message_full = null;
							}
						}

						// We have to double check here because the templates could be missing
						if (isset($notification_emails[$cur_subscriber['language']]))
						{
							if ($cur_subscriber['notify_with_post'] == '0')
								DBC_mail($cur_subscriber['email'], $notification_emails[$cur_subscriber['language']][0], $notification_emails[$cur_subscriber['language']][1]);
							else
								DBC_mail($cur_subscriber['email'], $notification_emails[$cur_subscriber['language']][2], $notification_emails[$cur_subscriber['language']][3]);
						}
					}
				}
			}
		}
		// If it's a new topic
		else if ($fid)
		{
			$stick_fp = ($is_admmod && isset($_POST['stickfp'])) ? 1 : 0;
			// Create the topic
			$db->query('INSERT INTO '.$db->prefix.'topics (stick_fp, poster, subject, topic_desc, posted, last_post, last_poster, last_poster_id, forum_id) VALUES('.$stick_fp.', \''.$db->escape($username).'\', \''.$db->escape($subject).'\', \''.$db->escape($topic_desc).'\' , '.$now.', '.$now.', \''.$db->escape($username).'\', \''.$db->escape($id).'\', '.$fid.')') or error('Unable to create topic', __FILE__, __LINE__, $db->error());
			$new_tid = $db->insert_id();

			if (!$DBC_user['is_guest'])
			{
				// To subscribe or not to subscribe, that ...
				if ($DBC_config['o_subscriptions'] == '1' && $subscribe)
					$db->query('INSERT INTO '.$db->prefix.'subscriptions (user_id, topic_id) VALUES('.$DBC_user['id'].' ,'.$new_tid.')') or error('Unable to add subscription', __FILE__, __LINE__, $db->error());

				// Create the post ("topic post")
				$db->query('INSERT INTO '.$db->prefix.'posts (poster, poster_id, poster_ip, message, hide_smilies, posted, topic_id, user_agent) VALUES(\''.$db->escape($username).'\', '.$DBC_user['id'].', \''.get_remote_address().'\', \''.$db->escape($message).'\', '.$hide_smilies.', '.$now.', '.$new_tid.', \''.$db->escape($_SERVER['HTTP_USER_AGENT']).'\')') or error('Unable to create post', __FILE__, __LINE__, $db->error());
			}
			else
			{
				// Create the post ("topic post")
				$email_sql = ($DBC_config['p_force_guest_email'] == '1' || $email != '') ? '\''.$email.'\'' : 'NULL';
				$db->query('INSERT INTO '.$db->prefix.'posts (poster, poster_ip, poster_email, message, hide_smilies, posted, topic_id, user_agent) VALUES(\''.$db->escape($username).'\', \''.get_remote_address().'\', '.$email_sql.', \''.$db->escape($message).'\', '.$hide_smilies.', '.$now.', '.$new_tid.', \''.$db->escape($_SERVER['HTTP_USER_AGENT']).'\')') or error('Unable to create post', __FILE__, __LINE__, $db->error());
			}
			$new_pid = $db->insert_id();

			// Update the topic with last_post_id
			$db->query('UPDATE '.$db->prefix.'topics SET last_post_id='.$new_pid.', first_post_id='.$new_pid.' WHERE id='.$new_tid) or error('Unable to update topic', __FILE__, __LINE__, $db->error());

			update_search_index('post', $new_pid, $message, $subject, $topic_desc);

			update_forum($fid);
		}

		// If we previously found out that the email was banned
		if ($DBC_user['is_guest'] && $banned_email && $DBC_config['o_mailing_list'] != '')
		{
			$mail_subject = $lang_common['Banned email notification'];
			$mail_message = sprintf($lang_common['Banned email post message'], $username, $email)."\n";
			$mail_message .= sprintf($lang_common['Post URL'], $DBC_config['o_base_url'].'/topics_'.$new_pid.'#p'.$new_pid)."\n";
			$mail_message .= "\n".'--'."\n".$lang_common['Email signature'];

			DBC_mail($DBC_config['o_mailing_list'], $mail_subject, $mail_message);
		}

		// If the posting user is logged in, increment his/her post count
		if (!$DBC_user['is_guest'])
		{
			// START Merge post
			if (!$merged && $cur_posting['no_sum_mess'] == 0)
				$db->query('UPDATE '.$db->prefix.'users SET num_posts=num_posts+1, last_post='.$now.' WHERE id='.$DBC_user['id']) or error('Unable to update user', __FILE__, __LINE__, $db->error());
      else
				$db->query('UPDATE '.$db->prefix.'users SET last_post='.$now.' WHERE id='.$DBC_user['id']) or error('Unable to update user', __FILE__, __LINE__, $db->error());
			// END Merge post

			$tracked_topics = get_tracked_topics();
			$tracked_topics['topics'][$new_tid] = time();
			set_tracked_topics($tracked_topics);
		}
		else
		{
			$db->query('UPDATE '.$db->prefix.'online SET last_post='.$now.' WHERE ident=\''.$db->escape(get_remote_address()).'\'' ) or error('Unable to update user', __FILE__, __LINE__, $db->error());
		}
		if (isset($_GET['ajax']) && isset($_GET['lpid']))
			header('Location: viewtopic.php?ajax&id='.$tid.'&pcount='.intval($_GET['pcount']).'&lpid='.intval($_GET['lpid']));
		redirect('topics_'.$new_pid.'#p'.$new_pid, $lang_post['Post redirect']);
	}
}

if (isset($_GET['ajax']) && !empty($errors))
	exit(implode("\n", $errors));


// If a topic ID was specified in the url (it's a reply)
if ($tid)
{
	$action = $lang_post['Post a reply'];
	$form = '<form id="post" method="post" action="post.php?action=post&amp;tid='.$tid.'" onsubmit="this.submit.disabled=true;if(process_form(this)){return true;}else{this.submit.disabled=false;return false;}">';

	// If a quote ID was specified in the url
	if (isset($_GET['qid']))
	{
		$qid = intval($_GET['qid']);
		if ($qid < 1)
			message($lang_common['Bad request']);

		$result = $db->query('SELECT poster, message FROM '.$db->prefix.'posts WHERE id='.$qid.' AND topic_id='.$tid) or error('Unable to fetch quote info', __FILE__, __LINE__, $db->error());
		if (!$db->num_rows($result))
			message($lang_common['Bad request']);

		list($q_poster, $q_message) = $db->fetch_row($result);

//		$q_message = preg_replace('%\[img(?:=.*?)?\]%', '[url]', $q_message);
//		$q_message = str_replace('[/img]', '[/url]', $q_message);

		if ($DBC_config['o_censoring'] == '1')
			$q_message = censor_words($q_message);

		$q_message = DBC_htmlspecialchars($q_message);
		$q_message = preg_replace("#\[hide](.+?)\[/hide\]#is", '[b][[i]'.$lang_topic['Hidden text'].'.[/i]][/b]', $q_message);


		if ($DBC_config['p_message_bbcode'] == '1')
		{
			// If username contains a square bracket, we add "" or '' around it (so we know when it starts and ends)
			if (strpos($q_poster, '[') !== false || strpos($q_poster, ']') !== false)
			{
				if (strpos($q_poster, '\'') !== false)
					$q_poster = '"'.$q_poster.'"';
				else
					$q_poster = '\''.$q_poster.'\'';
			}
			else
			{
				// Get the characters at the start and end of $q_poster
				$ends = substr($q_poster, 0, 1).substr($q_poster, -1, 1);

				// Deal with quoting "Username" or 'Username' (becomes '"Username"' or "'Username'")
				if ($ends == '\'\'')
					$q_poster = '"'.$q_poster.'"';
				else if ($ends == '""')
					$q_poster = '\''.$q_poster.'\'';
			}

			$quote = '[quote='.$q_poster.']'.$q_message.'[/quote]'."\n";
		}
		else
			$quote = '> '.$q_poster.' '.$lang_common['wrote']."\n\n".'> '.$q_message."\n";
	}
}
// If a forum ID was specified in the url (new topic)
else if ($fid)
{
	$action = $lang_post['Post new topic'];
	$form = '<form id="post" method="post" action="post.php?action=post&amp;fid='.$fid.'" onsubmit="return process_form(this)">';
}
else
	message($lang_common['Bad request']);

$page_head['bbcode'] = '<script type="text/javascript" src="engine/classes/js/post.js"></script>';

$page_title = array(DBC_htmlspecialchars($DBC_config['o_board_title']), $action);
$required_fields = array('req_email' => $lang_common['Email'], 'req_subject' => $lang_common['Subject'], 'req_topic_desc' => $lang_common['topic_desc'], 'req_message' => $lang_common['Message']);
$focus_element = array('post');

if (!$DBC_user['is_guest'])
	$focus_element[] = ($fid) ? 'req_subject' : 'req_message';
else
{
	$required_fields['req_username'] = $lang_post['Guest name'];
	$focus_element[] = 'req_username';
}

define('DBC_ACTIVE_PAGE', 'index');
define('DBC_POST', 1);
require DBC_ROOT.'engine/engine.php';

?>


<div id="sec_nav_con"><div id="sec_nav_left"><div id="sec_nav_right"><div id="secondary_nav">
<ul id="breadcrumb" class="left">

<li class="first"><a href="index.php">Форум</a></li>
<li><span>»&#160;</span><a href="forum_<?php echo $cur_posting['id'] ?>"><?php echo DBC_htmlspecialchars($cur_posting['forum_name']) ?></a></li>
<?php if (isset($cur_posting['subject'])): ?><li><span>»&#160;</span><a href="topic_<?php echo $tid ?>"><?php echo DBC_htmlspecialchars($cur_posting['subject']) ?></a></li>
<?php endif; ?>			<li><span>»&#160;</span><strong><?php echo $action ?></strong></li>
</ul>
<ul id="section_links" class="right"></ul><br class="clear">
</div></div></div></div><br/>

<?php

// If there are errors, we display them
if (!empty($errors))
{
	if ($DBC_user['is_guest'] && $DBC_config['o_blocking_time'] != '0')
	{
		$db->query('INSERT INTO '.$db->prefix.'blocking (block_ip, block_log, block_type) VALUES(\''.$db->escape(get_remote_address()).'\', '.time().', 3)') or error('Unable to create blocking', __FILE__, __LINE__, $db->error());

		$block_kolvo = $block_kolvo + 1;
		if ($block_kolvo > $DBC_config['o_blocking_kolvo'] && $DBC_config['o_blocking_user'] != '1')
		{
			$reason = '[MOD] Auto Bloking. Error input post.php'."\n\n".'IP = '.get_remote_address()."\n".'UserName = '.$username."\n".'Email = '.$email."\n";
			// Should we use the internal report handling?
			if ($DBC_config['o_report_method'] == '0' || $DBC_config['o_report_method'] == '2')
				$db->query('INSERT INTO '.$db->prefix.'reports (post_id, topic_id, forum_id, reported_by, created, message) VALUES(0, 0, 0, '.$DBC_user['id'].', '.time().', \''.$db->escape($reason).'\')' ) or error('Unable to create report', __FILE__, __LINE__, $db->error());

			message($lang_common['Limit of errors']);
		}
	}

?>


<div id="posterror" class="block">
	<div class="box">
		<div class="inbox error-info">
			<p><?php echo $lang_post['Post errors info'] ?></p>
			<ul class="error-list">
<?php

	foreach ($errors as $cur_error)
		echo "\t\t\t\t".'<li><strong>'.$cur_error.'</strong></li>'."\n";
?>
			</ul>
		</div>
	</div>
</div>


<?php

}
else if (isset($_POST['preview']))
{
	require_once DBC_ROOT.'engine/parser.php';
	$preview_message = parse_message($message, $hide_smilies);

?>

<table width="100%" height="38" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="28" class="bg_forum_title_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_title_center"><span class="cat_title"><?php echo $lang_post['Post preview'] ?></span></td>
<td align="center" width="28" class="bg_forum_title_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
</tr></table>

<table class="forum_adv_table"  width="100%" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" class="forum_adv_tleft" width="2"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" width="100%"><div class="forum_adv_c"><br/>

	<div class="box">
		<div class="inbox">
			<div class="postbody">
				<div class="postright">
					<div class="postmsg">
						<?php echo $preview_message."\n" ?>
					</div>
				</div>
			</div>
		</div>
	</div>

</div></td>
<td align="left" class="forum_adv_tright" width="2"><img src="engine/skins/images/spacer.gif" border="0"></td>
</td></tr></table>
<table width="100%" height="23" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="30" class="bg_forum_bott_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_bott_center"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="center" width="30" class="bg_forum_bott_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
</tr></thead></table>


<?php

}


$cur_index = 1;

?>


<table width="100%" height="38" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="28" class="bg_forum_title_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_title_center"><span class="cat_title"><?php echo $action ?></span></td>
<td align="center" width="28" class="bg_forum_title_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
</tr></table>

<table class="forum_adv_table"  width="100%" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" class="forum_adv_tleft" width="2"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" width="100%"><div class="forum_adv2"><div style="padding: 0px 25px 0px 25px;">

<?php echo $form."\n" ?>
						<input id="form_sent" type="hidden" name="form_sent" value="1" />
						<input type="hidden" name="form_user" value="<?php echo (!$DBC_user['is_guest']) ? DBC_htmlspecialchars($DBC_user['username']) : 'Guest'; ?>" />
	<table class="tableform">


<?php

if ($DBC_user['is_guest'])
{
	$email_label = ($DBC_config['p_force_guest_email'] == '1') ? '<strong>'.$lang_common['Email'].' <span>'.$lang_common['Required'].'</span></strong>' : $lang_common['Email'];
	$email_form_name = ($DBC_config['p_force_guest_email'] == '1') ? 'req_email' : 'email';

?>
<input type="hidden" name="csrf_hash" value="<?php echo csrf_hash() ?>" />


		<tr class="fieldtr">

			<td class="label"><?php echo $lang_post['Guest name'] ?></td>
			<td><input type="text" name="req_username" value="<?php if (isset($_POST['req_username'])) echo DBC_htmlspecialchars($username); ?>" size="25" maxlength="25" class="f_input" tabindex="<?php echo $cur_index++ ?>" />
			</td>
		</tr>

		<tr class="fieldtr">

			<td class="label"><?php echo $email_label ?></td>
			<td><input type="text" name="<?php echo $email_form_name ?>" value="<?php if (isset($_POST[$email_form_name])) echo DBC_htmlspecialchars($email); ?>" size="50" class="f_input" maxlength="80" tabindex="<?php echo $cur_index++ ?>" />
			</td>
		</tr>

<?php

}

if ($fid): ?>



		<tr class="fieldtr">

			<td class="label"><?php echo $lang_common['Subject'] ?></td>
			<td><input class="f_input" type="text" name="req_subject" value="<?php if (isset($_POST['req_subject'])) echo DBC_htmlspecialchars($subject); ?>" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" />
			</td>
		</tr>

		<tr class="fieldtr">

			<td class="label"><?php echo $lang_common['topic_desc'] ?></td>
			<td><input class="f_input" type="text" name="topic_desc" value="<?php if (isset($_POST['topic_desc'])) echo DBC_htmlspecialchars($topic_desc); ?>" size="80" maxlength="70" tabindex="<?php echo $cur_index++ ?>" />
			</td>
		</tr>
<?php endif; ?>
<script type="text/javascript">
	jQuery(function()
	{
		jQuery('textarea').autoResize();
	});
</script>
		<tr class="fieldtr">

			<td class="label"><span class="conl<?php echo ($DBC_config['p_force_guest_email'] == '1') ? ' required' : '' ?>"><?php echo $lang_common['Message'] ?></span></td>
			<td><div width="100%" id="bbcode_bar"></div><textarea name="req_message" id="req_message" rows="20" cols="95" width="100%" class="f_editor  message" tabindex="<?php echo $cur_index++ ?>"><?php echo isset($_POST['req_message']) ? DBC_htmlspecialchars($message) : (isset($quote) ? $quote : ''); ?></textarea>
													<ul class="bblinks">
							<li><span><a href="help.php#bbcode" onclick="window.open(this.href); return false;"><?php echo $lang_common['BBCode'] ?></a> <?php echo ($DBC_config['p_message_bbcode'] == '1') ? $lang_common['on'] : $lang_common['off']; ?></span></li>
							<li><span><a href="help.php#img" onclick="window.open(this.href); return false;"><?php echo $lang_common['img tag'] ?></a> <?php echo ($DBC_config['p_message_img_tag'] == '1') ? $lang_common['on'] : $lang_common['off']; ?></span></li>
							<li><span><a href="help.php#smilies" onclick="window.open(this.href); return false;"><?php echo $lang_common['Smilies'] ?></a> <?php echo ($DBC_config['o_smilies'] == '1') ? $lang_common['on'] : $lang_common['off']; ?></span></li>
						</ul>
		</td>
		</tr>
<?php

$checkboxes = array();
if (!$DBC_user['is_guest'])
{
	if ($DBC_config['o_smilies'] == '1')
		$checkboxes[] = '<label><input type="checkbox" name="hide_smilies" value="1" tabindex="'.($cur_index++).'"'.(isset($_POST['hide_smilies']) ? ' checked="checked"' : '').' />'.$lang_post['Hide smilies'].'<br /></label>';

	if ($DBC_config['o_subscriptions'] == '1')
	{
		$subscr_checked = false;

		// If it's a preview
		if (isset($_POST['preview']))
			$subscr_checked = isset($_POST['subscribe']) ? true : false;
		// If auto subscribed
		else if ($DBC_user['auto_notify'])
			$subscr_checked = true;
		// If already subscribed to the topic
		else if ($is_subscribed)
			$subscr_checked = true;

		$checkboxes[] = '<label><input type="checkbox" name="subscribe" value="1" tabindex="'.($cur_index++).'"'.($subscr_checked ? ' checked="checked"' : '').' />'.($is_subscribed ? $lang_post['Stay subscribed'] : $lang_post['Subscribe']).'<br /></label>';
	}
	// START Merge mod
	if ($is_admmod && !$fid)
		$checkboxes[] = '<label><input type="checkbox" name="merge" value="1" tabindex="'.($cur_index++).'"'.((isset($_POST['merge']) || (!isset($_POST['merge']) && !isset($_POST['form_sent']))) ? ' checked="checked"' : '').' />'.$lang_post['Merge posts'].'<br /></label>';
	// End Merge mod

	if ($is_admmod && $fid)
		$checkboxes[] = '<label><input type="checkbox" name="stickfp" value="1" tabindex="'.($cur_index++).'"'.((isset($_POST['stickfp'])) ? ' checked="checked"' : '').' />'.$lang_post['Stick first post'].'<br /></label>';

}
else if ($DBC_config['o_smilies'] == '1')
	$checkboxes[] = '<label><input type="checkbox" name="hide_smilies" value="1" tabindex="'.($cur_index++).'"'.(isset($_POST['hide_smilies']) ? ' checked="checked"' : '').' />'.$lang_post['Hide smilies'].'<br /></label>';
if (!empty($checkboxes))
{

?>
		<tr class="fieldtr">

			<td class="label"><?php echo $lang_common['Options'] ?></td>
			<td><?php echo implode("\n\t\t\t\t\t\t\t", $checkboxes)."\n" ?>
			</td>
		</tr>

<?php

}

?>

		<tr class="fieldtr">

			<td class="label"></td>
			<td>			<p class="buttons"><input class="fbutton" type="submit"  name="submit" value="<?php echo $lang_common['Submit'] ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="s" /> <input class="fbutton" type="submit" name="preview" value="<?php echo $lang_post['Preview'] ?>" tabindex="<?php echo $cur_index++ ?>" accesskey="p" /> <a href="javascript:history.go(-1)"><?php echo $lang_common['Go back'] ?></a></p>

			</td>
		</tr>


	</table>
	</div>
</form>






<br/>
</div></td>
<td align="left" class="forum_adv_tright" width="2"><img src="engine/skins/images/spacer.gif" border="0"></td>
</td></tr></table>
<table width="100%" height="23" border="0" cellpadding="0" cellspacing="0"><thead><tr>
<td align="left" width="30" class="bg_forum_bott_left"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="left" class="bg_forum_bott_center"><img src="engine/skins/images/spacer.gif" border="0"></td>
<td align="center" width="30" class="bg_forum_bott_right"><img src="engine/skins/images/spacer.gif" border="0"></td>
</tr></thead></table>

<?php
require DBC_ROOT.'engine/bbcode.inc.php';

if ($DBC_user['is_guest'])
	echo '<script type="text/javascript">document.getElementById(\'form_sent\').value=\''.time().'\';</script>';

// Check to see if the topic review is to be displayed
if ($tid && $DBC_config['o_topic_review'] != '0')
{
	require_once DBC_ROOT.'engine/parser.php';

	$result = $db->query('SELECT poster, message, hide_smilies, posted FROM '.$db->prefix.'posts WHERE topic_id='.$tid.' ORDER BY id DESC LIMIT '.$DBC_config['o_topic_review']) or error('Unable to fetch topic review', __FILE__, __LINE__, $db->error());

?>

<div id="postreview">
	<h2><span><?php echo $lang_post['Topic review'] ?></span></h2>
<?php

	// Set background switching on
	$post_count = 0;

	while ($cur_post = $db->fetch_assoc($result))
	{
		$post_count++;

		$cur_post['message'] = parse_message($cur_post['message'], $cur_post['hide_smilies']);

?>
	<div class="blockpost">
		<div class="box<?php echo ($post_count % 2 == 0) ? ' roweven' : ' rowodd' ?>">
			<div class="inbox">
				<div class="postbody">
					<div class="postleft">
						<dl>
							<dt><strong><?php echo DBC_htmlspecialchars($cur_post['poster']) ?></strong></dt>
							<dd><span><?php echo format_time($cur_post['posted']) ?></span></dd>
						</dl>
					</div>
					<div class="postright">
						<div class="postmsg">
							<?php echo $cur_post['message']."\n" ?>
						</div>
					</div>
				</div>
				<div class="clearer"></div>
			</div>
		</div>
	</div>
<?php

	}

?>
</div>
<?php

}

$footer_style = 'index';
require DBC_ROOT.'engine/footer.php';
